package com.atguigu.springcloud.controller;


import java.util.List;

import javax.annotation.Resource;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.atguigu.springcloud.config.loadbakanced.LoadBanced;
import com.atguigu.springcloud.entity.CommonResult;
import com.atguigu.springcloud.entity.Payment;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
@Api("OrderController")
@RequestMapping(value = "/consumer")
public class OrderController {
	@Resource
	private RestTemplate restTemplate;
	
	/*使用自定义负债均衡
	@Resource private LoadBanced loadBanced;
	@Resource private DiscoveryClient discoveryClient;
	*/
	private  final String pay_url = "http://CLOUD-PAYMENT-SERVICE";
	@ApiOperation("插入")
	@PostMapping(value = "/create")
	public CommonResult create(@RequestBody Payment payment) {
		log.info("插入：" +payment);
		return restTemplate.postForObject(pay_url+"/payment/create", payment, CommonResult.class);
	}
	@ApiOperation("查询")
	@GetMapping(value = "/get/{id}")
	public CommonResult get(@PathVariable long id) {
		log.info("查询：" );
		return restTemplate.getForObject(pay_url+"/payment/get/"+id,  CommonResult.class);
	}
	@ApiOperation("restTemplate.getForEntity 使用示例")
	@GetMapping(value = "/getForEntity/{id}")
	public CommonResult getForEntity(@PathVariable long id) {
		log.info("查询：" );
		ResponseEntity<CommonResult> responseEntity = restTemplate.getForEntity(pay_url+"/payment/get/"+id,  CommonResult.class);
		if(responseEntity.getStatusCode().is2xxSuccessful()) {
			return CommonResult.ok(responseEntity.getBody());
		}else {
			return CommonResult.error(responseEntity.getStatusCodeValue(),"调用失败");
		}
	}
	/*@ApiOperation("测试自定义负载均衡轮询算法")
	@GetMapping(value = "/lb")
	public CommonResult lb() {
		List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
		if(instances == null ||instances.size()<=0) {
			return CommonResult.error("没有足够的服务可以访问！");
		}
		
		ServiceInstance instance = loadBanced.instance(instances);
		return restTemplate.getForObject(instance.getUri()+"/payment/info",  CommonResult.class);
	}*/
}
